package com.imooc.order.controller;

import com.imooc.order.convert.OrderForm2OrderDTO;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.form.OrderForm;
import com.imooc.order.service.OrderService;
import com.imooc.order.util.ResultVOUtil;
import com.imooc.order.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author steve
 * @date 2020/6/16 12:02
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 1. 参数检验
     * 2. 查询商品信息（调用商品服务）
     * 3. 计算总价
     * 4. 扣减库存
     * 5. 订单入库
     * @return
     */
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        //1. 校验参数
        if (bindingResult.hasErrors()) {
            //参数校验有误，则打印日志和抛异常
            log.info("【创建订单】 参数不正确 OrderForm={}",orderForm);
            //返回异常码和异常信息
            throw new OrderException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }

        //orderForm -> orderDTO
        OrderDTO orderDTO = OrderForm2OrderDTO.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】 购物车信息为空");
            throw new OrderException(ResultEnum.CART_EMPYT);
        }

        //创建订单
        OrderDTO result = orderService.create(orderDTO);
               /*封装返回给前端的参数
        {
          "code": 0,
          "msg": "成功",
          "data": {
              "orderId": "147283992738221"
          }
        }
         */
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());
        return ResultVOUtil.success(map);
    }

    /**
     * 订单完结
     * @param orderId
     * @return
     */
    @PostMapping("/finish")
    public ResultVO<OrderDTO> finish(@RequestParam("orderId") String orderId) {
        OrderDTO orderDTO = orderService.finished(orderId);
        return ResultVOUtil.success(orderDTO);
    }

}
